package com.kwok.ssm.springmvc.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/file")
public class FileController {
    @RequestMapping("/upload")
    public String upload(MultipartFile source, HttpSession session){
        // 获取上传文件的原始文件名
        String originalFilename = source.getOriginalFilename();
        // 进行上传的文件名
        String uploadFileName = UUID.randomUUID().toString().replaceAll("-", "") + "_" + originalFilename;
        // 获取上传文件的目录(上传到本地磁盘)
//        String uploadPath = "D:\\upload";
        // 获取上传文件的目录(上传到Tomcat服务器)
        String realPath = session.getServletContext().getRealPath("/upload");
        System.out.println("文件上传的正式路径：" + realPath);
        // 创建目标文件
        File file = new File(realPath);
        if (! file.exists()) {
            // 如果目标文件不存在，则创建目标文件所在的目录
            file.mkdirs();
        }
        // 将上传的文件保存到指定目录
        try {
            source.transferTo(new File(file, uploadFileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "redirect:/jsp/success.jsp";
    }

    @RequestMapping("/download")
    public void download(String fileName, HttpSession session, HttpServletResponse response) {
        // 获取文件上传的真实路径
        String realPath = session.getServletContext().getRealPath("/upload");
        String path = realPath + "/" + fileName;
        // 设置响应头，告诉浏览器要以附件的形式保存下载内容 filename是浏览器显示的下载文件名
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        try {
            // 先读取到文件输入流，在写出到响应的输出流
            IOUtils.copy(new FileInputStream(path), response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
